package com.springboot.demo.utils;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.springboot.demo.entity.vo.ImageCodeVO;
import com.springboot.demo.exception.BusinessException;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.utils.CaptchaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.codec.digest.Md5Crypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;

/**
 * @author wubc683
 * @desc 图形验证码
 * @date 2021-08-19 15:49
 */
@Component
@Slf4j
public class ImgCodeUtils {
    public static final String IMGCODEPREFIX = "IMGCODE::";
    // 图片验证码有效期(单位：秒）
    public static final Integer IMG_CODE_TIMEOUT = 300;
    @Autowired
    DefaultKaptcha defaultKaptcha;
    @Autowired
    RedisUtils redisUtils;

    public void create(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //生成验证码文字
        String kaptchaText = defaultKaptcha.createText();
        request.getSession().setAttribute(Constant.SESSION_IMGCODE, kaptchaText);
        request.getSession().setMaxInactiveInterval(IMG_CODE_TIMEOUT);
        log.info("图形验证码:{}", kaptchaText);
        //根据文字生成图片
        BufferedImage image = defaultKaptcha.createImage(kaptchaText);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        byte[] bytes = outputStream.toByteArray();
//        String encode = DigestUtils.md5Hex(kaptchaText);
//        Base64.Encoder encoder = Base64.getEncoder();
//        String imageData = "data:image/jpg;base64," + encoder.encodeToString(bytes);
        response.setContentType("image/jpg");
        OutputStream out = response.getOutputStream();
        out.write(bytes);
        out.flush();
        out.close();
    }
}
